package com.xiangban.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class FeignHeaderInterceptor implements RequestInterceptor {
    @Autowired
    private HttpServletRequest request;


    @Override
    public void apply(RequestTemplate template) {

        HttpServletRequest request = getServletRequest();
        if (null == request){
            return;
        }else {
            template.header("token", getHeaders(request));

        }

    }

    private HttpServletRequest getServletRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes== null){
            return null;
        }else {
            return servletRequestAttributes.getRequest();
        }

    }

    private String getHeaders(HttpServletRequest request){
        return request.getHeader("token");
    }


}